package info.niwota.profile;

import info.niwota.profile.ac.AccountListActivity;
import info.niwota.profile.contact.RecipientsActivity;
import info.niwota.profile.util.MailTemplate;
import info.niwota.webapp.InstallHotwebActivity;
import info.niwota.webapp.WebIntents;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.Toast;

public class MainActivity extends TabActivity implements OnClickListener {
	public static final String EXTRA_TAB = "extra.tab";
	private static final int[] TABS = new int[] { R.id.tab_btn_1, R.id.tab_btn_2, 
		R.id.tab_btn_3};
	
	private static final int[] TABS_ICON = new int[] {R.drawable.ic_icon_32, R.drawable.ic_recent_16,  R.drawable.ic_fav_16};
	private static final int[] TABS_ICON_DISABLED = new int[] {R.drawable.ic_icon_32, R.drawable.ic_recent_grey_16, R.drawable.ic_fav_grey_16};
	
	private static final String HELP_URI = "file:///android_asset/help.htm";

	private static final int RC_EDIT_PROFILE = 1;
	private static final int RC_LIST_PEER = 2;
	private static final int RC_PICK_PEER = 3;
	private static final int RC_SETTINGS = 4;
	private static final int RC_VIEW_PROFILE = 5;
	private static final int RC_PICK_FRIENDS = 6;
	private static final int RC_EDIT_SIGNATURE = 7;
	//private static final int RC_SEND = 8;
	
	private static final int SERVICE_ID = R.string.app_name;

	private static final String TAG = "MainActivity";
	
	private static void addNotification(Context ctx) {
		try {
			Notification note = new Notification(R.drawable.icon, null, 0);
			PendingIntent pi = PendingIntent.getActivity(ctx, 0, new Intent(
					ctx, MainActivity.class), 0);
			note.flags |= Notification.FLAG_NO_CLEAR;
			note.flags |= Notification.FLAG_ONGOING_EVENT;
			//
			CharSequence title = ctx.getText(R.string.app_name);
			CharSequence desc = ctx.getText(R.string.app_tagline);
			note.setLatestEventInfo(ctx, title, desc, pi);
			NotificationManager nm = (NotificationManager) ctx
					.getSystemService(Context.NOTIFICATION_SERVICE);
			nm.notify(SERVICE_ID, note);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void removeNotification(Context ctx) {
		try {
			NotificationManager nm = (NotificationManager) ctx
					.getSystemService(Context.NOTIFICATION_SERVICE);
			//
			nm.cancelAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doEditProfile() {
		try {
			Intent i = new Intent(this, EditProfileActivity.class);
			startActivityForResult(i, RC_EDIT_PROFILE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doHelp() {
		try {
			Intent i = new Intent(this, WebViewActivity.class);
			i.setData(Uri.parse(HELP_URI));
			startActivity(i);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unused")
	private void doListPeer() {
		try {
			if (InstallHotwebActivity.ensure(this)) {
				Intent i = new Intent();
				i.setClassName("info.niwota.web",
						"info.niwota.web.user.UserListActivity");
				startActivityForResult(i, RC_LIST_PEER);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unused")
	private void doPickPeer() {
		try {
			if (InstallHotwebActivity.ensure(this)) {
				Intent i = new Intent();
				i.setClassName("info.niwota.web",
						"info.niwota.web.user.PickUserActivity");
				startActivityForResult(i, RC_PICK_PEER);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doQuit() {
		if (Debug.DEBUG) {
			Log.d(TAG, "doQuit");
		}
		try {
			finish();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doSettings() {
		Intent i = new Intent(this, SettingsActivity.class);
		startActivityForResult(i, RC_SETTINGS);
	}

	private void doShowPeerProfile(Intent data) {
		String peer = data.getStringExtra(WebIntents.EXTRA_PEER);
		Intent i = new Intent(this, ViewProfileActivity.class);
		i.putExtra(WebIntents.EXTRA_PEER, peer);

		startActivityForResult(i, RC_VIEW_PROFILE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (Debug.DEBUG) {
			Log.d(TAG, "onActivityResult requestCode: " + requestCode
					+ " resultCode:" + resultCode + " == " + RESULT_OK
					+ " data: " + data);
		}

		switch (requestCode) {
		case RC_EDIT_PROFILE:
			// NOTE: photo change does not return correct result code
			// therefore we do not check it
			//
			//startLoad(false);
			break;
		case RC_SETTINGS:
			final Context ctx = this;
			if (Preferences.enableStatusbar(ctx)) {
				addNotification(ctx);
			} else {
				removeNotification(ctx);
			}
			break;
		case RC_PICK_PEER:
			if (resultCode == RESULT_OK) {
				doShowPeerProfile(data);
			}
			return;
		case RC_PICK_FRIENDS: 
			if (resultCode == RESULT_OK) {
				String emails = null;
				
				if (data != null) {
					Bundle extras = data.getExtras();
					if (extras != null) {
						emails = extras.getString(RecipientsActivity.EXTRA_EMAILS);
						
						//
						if (Debug.DEBUG) {
							Log.d(TAG, "emails: " + emails);
						}
					}
				}
				//
				updateFriends(emails);
			}
			return;
		default:
		}
	}

	private void updateFriends(String emails) {
		if (Debug.DEBUG) {
			Log.d(TAG, "updateFriends: "+emails);
		}
		Preferences.putFriends(this, emails);
		//
		//save to server?
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//
		forwardIfPeer();
		//
		init(savedInstanceState);
		
		addListeners();
	}

	private void addListeners() {
		
		for (int i = 0; i < TABS.length; i++) {
			Button bt = (Button) findViewById(TABS[i]);
			bt.setOnClickListener(this);
		}
	}

	private void init(Bundle savedInstanceState) {
		//
		setFullScreen();
		//
		setContentView(R.layout.main);

		// init tabs
		final TabHost tabHost = getTabHost();
		TabHost.TabSpec spec;
		Intent intent;

		//
		final String tab1 = getString(R.string.tab_profile);
		final String tab2 = getString(R.string.tab_recent);
		final String tab3 = getString(R.string.tab_favorites);

		// tab 1
		intent = new Intent().setClass(this, MyProfileActivity.class);
		spec = tabHost.newTabSpec(tab1).setIndicator(tab1);
		spec.setContent(intent);
		tabHost.addTab(spec);

		// tab2
		intent = new Intent().setClass(this, RecentListActivity.class);
		spec = tabHost.newTabSpec(tab2).setIndicator(tab2);
		spec.setContent(intent);
		tabHost.addTab(spec);

		// tab3
		intent = new Intent().setClass(this, FavoriteListActivity.class);
		spec = tabHost.newTabSpec(tab3).setIndicator(tab3);
		spec.setContent(intent);
		tabHost.addTab(spec);

		//
		// init
		//
		int tab = getIntent().getIntExtra(EXTRA_TAB, 0);
		setTab(tab);

		//
		tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			public void onTabChanged(String tabId) {
				hideKeyboard(tabHost);
			}
		});

		//
		if (Debug.DEBUG) {
			Log.d(TAG, "onCreate done.");
		}
		//
	}

	private void setFullScreen() {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}

	private void hideKeyboard(View v) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
	}

	private void forwardIfPeer() {
		Intent data = getIntent();
		String pid = data.getStringExtra(WebIntents.EXTRA_PEER);

		if (Debug.DEBUG) {
			Log.d(TAG,
					"forwardIfPeer peer: " + pid + " extras: "
							+ data.getExtras());
		}
		if (!TextUtils.isEmpty(pid)) {
			// forward
			Intent i = new Intent(this, ViewProfileActivity.class);
			i.putExtra(WebIntents.EXTRA_PEER, pid);
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_FORWARD_RESULT);
			startActivity(i);
			finish();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_option, menu);
		//
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case R.id.profile_friends_opt_menu_id:
			doAccountList();
			break;
		case R.id.profile_permission_opt_menu_id:
			doPermission();
			break;
//		case R.id.profile_peers_opt_menu_id:
//			doPickPeer();
//			break;
//		case R.id.profile_add_opt_menu_id:
//			doListPeer();
//			break;
		case R.id.profile_edit_profile_opt_menu_id:
			doEditProfile();
			break;
		case R.id.profile_edit_signature_opt_menu_id:
			doEditSignaturefile();
			break;
		case R.id.profile_quit_opt_menu_id:
			doQuit();
			break;
		case R.id.profile_settings_opt_menu_id:
			doSettings();
			break;
		case R.id.profile_help_opt_menu_id:
			doHelp();
			break;
		case R.id.profile_send_opt_menu_id:
			doSend();
			break;
		default:
			return false;
		}
		return true;
	}

	private void doSend() {
		final Context ctx = this;
		final boolean[] option = new boolean[] {false};
		
		AlertDialog builder = new AlertDialog.Builder(ctx).setCancelable(true)	
				.setTitle(R.string.action_send)
				.setMultiChoiceItems(R.array.send_profile_option, option,
						new DialogInterface.OnMultiChoiceClickListener() {
							public void onClick(DialogInterface dialog,
									int which, boolean isChecked) {
								option[which] = isChecked;
							}
						})
				.setPositiveButton(R.string.action_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								sendProfile(null, option[0]);
							}
						}).create();

		builder.show();
	}
	
	private void sendProfile(String email, boolean profile) {
		try {
			MailTemplate.startSendActivity(this, email, profile);
		} catch (Exception e) {
			Toast.makeText(this, "" + e, Toast.LENGTH_SHORT).show();
		}
	}

	private void doEditSignaturefile() {
		try {
			Intent i = new Intent(this, EditSignatureActivity.class);
			startActivityForResult(i, RC_EDIT_SIGNATURE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doAccountList() {
		try {
			Intent i = new Intent(this, AccountListActivity.class);
			startActivity(i);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doPermission() {
		Intent i = new Intent(this, RecipientsActivity.class);
		String emails = Preferences.getFriends(this);
		
		i.putExtra(RecipientsActivity.EXTRA_EMAILS, emails);

		startActivityForResult(i, RC_PICK_FRIENDS);
	}

	@Override
	protected void onResume() {
		if (Debug.DEBUG) {
			Log.d(TAG, "resume intent: " + getIntent());
		}
		forwardIfPeer();

		super.onResume();
	}

	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.tab_btn_1:
			setTab(0);
			break;
		case R.id.tab_btn_2:
			setTab(1);
			break;
		case R.id.tab_btn_3:
			setTab(2);
			break;
		default:
			break;
		}
	
	}
	private void setTab(int tab) {
		getTabHost().setCurrentTab(tab);
		for (int i = 1; i < TABS.length; i++) {
			Button bt = (Button) findViewById(TABS[i]);
			int d = (i != tab ? TABS_ICON[i] : TABS_ICON_DISABLED[i]);
			bt.setCompoundDrawablesWithIntrinsicBounds(d, 0, 0, 0);
		}
	}
}